﻿using BlondeHeaven.DB;
using BlondeHeaven.DB.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace BlondeHeaven.DAL
{
    public class DalUserService<T> : IDalUserService<T> where T : User, new()
    {
        /// <summary>
        /// 数据访问层：DAL
        /// </summary>
        /// <typeparam name="T"></typeparam>


        private BHDbContext _bHDbContext;

        /// <summary>
        /// 获得数据库上下文
        /// </summary>
        /// <param name="dbContext">数据库上下文类，各自更改成自己的</param>
        public DalUserService(BHDbContext bHDbContext)
        {
            _bHDbContext = bHDbContext;
        }

        public T Add(T model)
        {
            _bHDbContext.Set<T>().Add(model);
            return model;
        }
        public int SaveChanges()
        {
            return _bHDbContext.SaveChanges();
        }

        public IQueryable<T> GetAll()
        {
            return _bHDbContext.Set<T>().Where(m => !m.IsRemo).AsNoTracking();
        }
        public async Task<T> GetOneById(int Id)
        {
            return await GetAll().FirstAsync(m => m.Id == Id);
        }
        public async Task EditAsync(T model, bool saved = true)
        {
            _bHDbContext.Entry(model).State = EntityState.Modified;

            if (saved)
            {
                await _bHDbContext.SaveChangesAsync();
            }
        }
        public async Task RemoveAsync(bool saved = true)
        {
            User user = new User();
            user.IsRemo = true;
            _bHDbContext.Entry(user).State = EntityState.Modified;
            if (saved)
            {
                await _bHDbContext.SaveChangesAsync();
            }

        }


    }
}

